<script setup>
  import { computed, ref, isRef, watch } from 'vue'
  import { storeToRefs } from 'pinia'
  import FileUpload from '@/components/forms/FileUpload.vue'
  import Select from '@/components/forms/Select.vue'
  import Input from '@/components/forms/Input.vue'
  import { useField } from 'vee-validate'
  import { NODE_TYPE_LABELS } from '@/helpers/node'
  import { useSaleFileStore } from '@/stores/saleFiles'
  import { useIndicatorStore } from '@/stores/indicators'

  const props = defineProps({
    file: { type: Object, default: '' },
    fileTypeOptions: { type: Array, default: [] },
    parentOptions: { type: Array, default: [] },
    fileRequirements: { type: Array, default: [] },
    maxFileSize: { type: Number },
  })

  // Données du formulaire (vee-validate)
  const { value: currentParentType } = useField('parent_type')
  const {
    value: currentParentId,
    setValue: setParentValue,
    setTouched: setParentTouched,
  } = useField('parent_id')

  const { value: currentFileTypeId, setValue: setFileTypeId } =
    useField('file_type_id')
  const { setValue: setIndicatorId } = useField('indicator_id')
  const { setTouched, setValue } = useField('description')

  const store = useSaleFileStore()

  let fileUrl = null
  if (props.file) {
    fileUrl = `/files/${props.file.id}?action=download`
  }

  // Filtre les types de fichiers via le parentId et le fileTypeId
  const getFileType = (parentId) => {
    const fileRequirements = store.getIndicators(parentId)

    const result = []
    if (fileRequirements) {
      for (const req of fileRequirements) {
        result.push(req.file_type)
      }
    }
    return result
  }
  const filteredFileTypeOptions = ref(getFileType(currentParentId.value))
  ////////////////////////////////////////////////////////////////////////

  // Set la description avec le nom du fichier
  const onFileSelected = (fileObject) => {
    if (fileObject.name) {
      setValue(fileObject.name)
      setTouched()
    }
  }
  /////////////////////////////////////////////

  // Convertit les types de Node (Project/Affaires/Devis,Factures)
  // en options avec libellé
  const parentTypeOptions = computed(() => {
    const parentTypes = props.parentOptions.map((item) => item.type_)
    const arrayOptions = Object.entries(NODE_TYPE_LABELS).filter((entry) =>
      parentTypes.includes(entry[0])
    )
    return arrayOptions.map((item) => {
      return { name: item[0], value: item[1] }
    })
  })
  ////////////////////////////////////////////////////////////////////////

  // Filtre les parents (affaires/Task, Project ...)
  const filteredParentOptions = (value) => {
    if (isRef(value)) {
      value = value.value
    }
    return props.parentOptions.filter((item) => item.type_ === value)
  }
  const parentOptions = ref(filteredParentOptions(currentParentType))
  ///////////////////////////////////////////////////////////////////////////

  // Update les parents quand le type change
  const onParentTypeChange = (value) => {
    parentOptions.value = filteredParentOptions(value)
    if (parentOptions.value.length === 1) {
      setParentValue(parentOptions.value[0].id)
    }
    setParentTouched(true)
    filteredFileTypeOptions.value = []
    setFileTypeId(null)
  }
  watch(currentParentType, onParentTypeChange)
  ///////////////////////////////////////////////////////////////////////////

  // Update les types de fichiers quand le parent change
  watch(currentParentId, (value) => {
    filteredFileTypeOptions.value = getFileType(value)
    setFileTypeId(null)
  })
  ////////////////////////////////////////////////////////

  // Set le indicator_id quand le filetype change
  const findIndicatorId = (value) => {
    const indicatorStore = useIndicatorStore()
    console.log('Finding the indicator with file type id: ', value)
    return indicatorStore.getByTypeId(value, currentParentId.value)
  }

  watch(currentFileTypeId, (value) => {
    const indicator = findIndicatorId(value)
    if (indicator) {
      setIndicatorId(indicator.id)
    } else {
      setIndicatorId(null)
    }
  })
  /////////////////////////////////////////////////
</script>
<template>
  <div>
    <div class="row form-row">
      <div class="col-md-6">
        <Select
          name="parent_type"
          label="Niveau d'attachement"
          :options="parentTypeOptions"
          :required="true"
          id-key="name"
          label-key="value"
        />
      </div>
      <div class="col-md-6">
        <Select
          name="parent_id"
          label="Attacher à ..."
          :options="parentOptions"
          id-key="id"
          label-key="name"
          :add-default="!currentParentId"
          :required="true"
        />
      </div>
    </div>
    <div class="row form-row">
      <div class="col-md-6">
        <FileUpload
          name="upload"
          label="Fichier"
          :file-info="file"
          :file-url="fileUrl"
          @changeValue="onFileSelected"
          :required="true"
          :maxSize="maxFileSize"
        />
      </div>
      <div class="col-md-6">
        <Select
          name="file_type_id"
          label="Type de fichier"
          :options="filteredFileTypeOptions"
          :add-default="true"
          :default-option="{ id: '', label: 'Aucun' }"
          id-key="id"
          label-key="label"
          description="Si ce fichier est requis pour ce type d’affaire ou ce document, choisissez le type de fichier requis. Si un fichier de ce type est déjà présent, il sera écrasé."
        />
        <Input name="indicator_id" type="hidden" />
      </div>
    </div>
    <div class="row form-row">
      <div class="col-md-12">
        <Input name="description" label="Description" :required="true" />
      </div>
    </div>
  </div>
</template>
